package Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Tools.LoginTools;

public class UserLoginServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);//调用自己的doPost方法
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1、设置请求对象中的编码格式
		req.setCharacterEncoding("UTF-8");
		//2、获取传入的账号及密码
		String username = req.getParameter("username");//获取账号
		String password = req.getParameter("password");//获取密码
		//3、获取数据库连接
		Connection conn = LoginTools.getConnection();
		//4、准备SQL
		String sql = "select * from users where username =? and password =?";
		//5、获取声明对象
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			//6、补全SQL
			ps.setString(1,username);
			ps.setString(2,password);
			//、z执行SQL并返回结果
			rs =ps.executeQuery();
			//8、解析结果集
			if(rs.next()) {
				//如果有数据就转发到首页
				req.getRequestDispatcher("WebPages/index.html").forward(req, resp);
			}else {
				//如果没有数据就重定向到注册页
				resp.sendRedirect("WebPages/register.html");
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			//9、关闭资源
			LoginTools.closeResource(conn, ps, rs);
		}
	}
}
